package com.wpml.netty.rpc;

import com.wpml.netty.rpc.common.PackMsg;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;


public class ResponseCallback {

    private static ConcurrentHashMap<Long, CompletableFuture<Object>> mapping = new ConcurrentHashMap<>();

    public static void addCallback(Long requestId, CompletableFuture<Object> callback) {
        System.out.println("注册回调 requestId = " + requestId);
        mapping.putIfAbsent(requestId, callback);
    }

    public static void runCallback(PackMsg packMsg) {
//        System.out.println("=========== runCallback ===========" + packMsg);
        CompletableFuture<Object> cf = mapping.get(packMsg.getHeader().getRequestID());
        cf.complete(packMsg.getContent().getRes());

        removeCB(packMsg.getHeader().getRequestID());
    }

    private static void removeCB(Long requestId) {
        mapping.remove(requestId);
    }
}
